package com.atguigu.actual.edu0417.unils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.hbase.client.Connection;
import redis.clients.jedis.Jedis;

import java.util.Objects;

/**
 * @author: techyang
 * @since: 2023-10-21 22:50
 * @description:
 **/
public class DimInfoUtil {

    /**
     * 通过旁路缓存获取维度信息
     * @param jedis
     * @param conn
     * @param namespace
     * @param tableName
     * @param rowKey
     * @return
     */
    public static JSONObject getDimInfo(Jedis jedis, Connection conn,String namespace, String tableName, String rowKey) {
        JSONObject dimInfoJsonObj = null;
        try {
            // 从Redis中获取dimInfo
            String redisKey = tableName + ":" + rowKey;
            String jsonStr = jedis.get(redisKey);
            if (StringUtils.isEmpty(jsonStr)) {
                // redis中没有获取到对应数据,从HBase中获取
                dimInfoJsonObj = HbaseUtil.getDimInfoFromHbase(conn, namespace, tableName, rowKey);
                if (Objects.nonNull(dimInfoJsonObj)) {
                    System.out.println("从HBase中获取到" + namespace + ":" + tableName + "表中(" + rowKey + ")的维度数据");
                    // 如果在HBase中获取到了维度信息,将对应的信息存入Redis中,并设置失效时间为1天
                    jedis.setex(redisKey,3600 * 24,dimInfoJsonObj.toJSONString());
                } else {
                    System.out.println("从HBase中<没有>获取到" + namespace + ":" + tableName + "表中(" + rowKey + ")的维度数据");
                }
            } else {
                dimInfoJsonObj = JSONObject.parseObject(jsonStr);
                System.out.println("从Redis中获取到" + namespace + ":" + tableName + "表中(" + rowKey + ")的维度数据");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("~~~从Redis中查询维度数据发生了异常~~~");
        }
        return dimInfoJsonObj;
    }



    public static void delRedisKey (String redisKey) {
        try (Jedis jedis = RedisUtil.getRedisClient()){
            jedis.del(redisKey);
            System.out.println("删除了<" + redisKey + ">的缓存信息");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




}
